<template>

    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container" :style="isPc ?'padding:30px': 'padding:10px'">

          <el-row :gutter="0">
            <el-col :md="4" :xs="24" style="margin:3px 0">
              <el-select v-model="query.cat_id" filterable  placeholder="分类"  clearable  class="handle-select mr10">
                <el-option v-for = "c in catArr" :key="c.Id" :label="c.Name" :value="c.Id" ></el-option>
              </el-select>
              <el-select v-model="query.state" placeholder="商品状态" clearable  class="handle-select">
                <el-option  key="1"  label="正常" value="1" ></el-option>
                <el-option  key="0"  label="已下线" value="0" ></el-option>
              </el-select>
            </el-col>
            <el-col :md="5" :xs="24" style="margin:3px 0">
              <el-select v-if="isPc" v-model="query.brand_id" style="width: 100%;margin-right: 5px" placeholder="品牌" clearable >
                <el-option v-for = "b in brandArr" :key="b.Id" :label="b.Name" :value="b.Id" ></el-option>
              </el-select>
            </el-col>
            <el-col :md="8" :xs="24" style="margin:3px 0">
              <el-input v-model="query.name" id="bar-code-input" style="width: 96%"  placeholder="商品名"></el-input>
            </el-col>
            <el-col :md="7" :xs="24" style="margin:3px 0">
              <el-button type="primary" icon="el-icon-search" @click="handleSearch" style="min-width:100px;margin-right: 10px">搜索</el-button>
            </el-col>
          </el-row>

            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                @sort-change="sortChange"
                header-cell-class-name="table-header"
            >
                <el-table-column v-if="isPc" prop="id" width="80px" label="Id"></el-table-column>
                <el-table-column v-if="isPc" prop="brand" width="100px" label="品牌"></el-table-column>
                <el-table-column prop="name" label="商品名称"   align="center"></el-table-column>
                <el-table-column v-if="isPc" prop="category"  label="分类"></el-table-column>
                <el-table-column label="操作" :width="isPc? '300px' : '75px'"  align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >修改
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-upload2"
                                :style="isPc? 'margin-left:10px': 'margin-left:0'"
                                @click="handleUpload(scope.$index, scope.row)"
                        >图片
                        </el-button>
                        <el-button
                                type="text"
                                v-if="isPc"
                                icon="el-icon-edit-outline"
                                style="padding: 2px 0"
                                @click="editDetail(scope.$index, scope.row)"
                        >详情
                        </el-button>
                        <el-button
                                type="text"
                                v-if="isPc"
                                :icon=" scope.row.state === '1' ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
                                @click="changeState(scope.row)"
                        >{{scope.row.state === '1' ? '下线' : '上线'}}
                        </el-button>
                        <el-button
                                v-if="isPc && scope.row.state === '0'"
                                type="text"
                                icon="el-icon-close"
                                @click="delSpu(scope.row)"
                        >删除
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination
                  background
                  :layout="isPc ? 'prev,next,pager' : 'prev,next'"
                  :current-page="query.pageIndex"
                  :page-size="query.pageSize"
                  :total="total"
                  @current-change="handlePageChange"
              ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="基本信息" :visible.sync="editVisible" :width="modalWidth"  :close-on-click-modal="false">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="标签">
                  <el-select v-model="form.type" placeholder="品牌" class="add-dialog-input mr10">
                    <el-option v-for = "(v, k) in typeArr" :key="k" :label="v" :value="k" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="form.cat_id" filterable placeholder="分类" class="add-dialog-input mr10">
                        <el-option v-for = "c in catArr" :key="c.Id" :label="c.Name" :value="c.Id" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="品牌">
                    <el-select v-model="form.brand_id" placeholder="品牌" class="add-dialog-input mr10">
                        <el-option v-for = "b in brandArr" :key="b.Id" :label="b.Name" :value="b.Id" ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="销量">
                    <el-input v-model="form.sales"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.home_pos"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="上传图片" :visible.sync="uploadVisible" :width="modalWidth"  :close-on-click-modal="false">
            <div><span>第几个图片做主图:</span><el-input style="width: 100px;margin-left: 10px" v-model="listImgIdx"></el-input></div>
            <el-upload
                    class="upload-demo"
                    accept="image/*"
                    action="https://upload-z2.qiniup.com"
                    :data="tokenData"
                    :on-remove="handleRemove"
                    :on-success="uploadOk"
                    :before-upload="beforeUpload"
                    :file-list="fileList"
                    list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelUpload">取 消</el-button>
                <el-button type="primary" @click="saveUpload">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="详情编辑" :visible.sync="detailVisible" width="520px"  :close-on-click-modal="false">
            <div class="rich_box">
                <quill-editor style="width:480px" v-model="detailContent" :options="editorOption" ref="QuillEditor"></quill-editor>
            </div>
            <el-upload
                    class="edit-uploader"
                    action="https://upload-z2.qiniup.com"
                    :data="tokenData"
                    :on-success="editUploadOk"
                    :before-upload="beforeEditUpload"
                    :show-file-list="false"
                    style="display: none"
            >
            <i class="el-icon-plus avatar-uploader-icon" id="imgInput"></i>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveDetail">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import imageConversion from 'image-conversion'
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import {quillEditor} from 'vue-quill-editor'

const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction
    [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    [{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    [{'font': []}],
    [{'align': []}],
    ['link', 'image', 'video'],
    ['clean']
];

export default {
    name: 'goods',
    data() {
        return {
            query: {
                cat_id: '',
                brand_id: '',
                name: '',
                orderBy: '',
                order: '',
                page: 1,
                pageSize: 10,
                state: '1',
                type: '0',
            },
            fileList: [],
            typeArr: {
              0: '普通',
              1: '秒杀',
              2: '新品',
              100: '积分',
            },
            imgList: [],
            tableData: [],
            catArr: [],
            brandArr: [],
            searchOptions: [],
            editVisible: false,
            uploadVisible: false,
            searchAttrVisible: false,
            editAttrVisible: false,
            editOptions: [],
            addAttrArr: [],
            form: {
                sales: '',
                price: '',
                home_pos: '',
                type: 0,
            },
            idx: -1,
            id: -1,
            uploadId: 0,
            detailId: 0,
            isPc: false,
            modalWidth: '80%',
            listImgIdx: 1,
            total: 0,
            detailVisible: false,
            detailContent: '',
            tokenData: {token: '', key: ''},
            qiniuUri: '',
            editorOption: {
                modules: {toolbar: {container: toolbarOptions, handlers: {
                    'image': function (value) {
                        if (value) {
                            document.querySelector('.edit-uploader input').click()
                        } else {
                            this.quill.format('image', false);
                        }
                    }}}}
            }
        };
    },
    components: {
        quillEditor
    },
    created() {
        if (document.body.clientWidth > 500) {
            this.modalWidth = '40%'
            this.isPc = true
        }
        this.getData();
        this.http.getCats().then(res => {
            this.catArr = res.data ? res.data : [];
        });
        this.http.getBrands().then(res => {
            this.brandArr = res.data ? res.data : [];
        });
        this.getQiuNiu()
    },
    activated(){
        this.getQiuNiu()
    },
    mounted(){
    },
    methods: {
        getQiuNiu(){
             this.http.qiniuToken().then(res => {
                this.tokenData.token = res.data.token
                this.qiniuUri = res.data.uri
            });
        },
        sortChange({ column, prop, order }){
            this.query.orderBy = prop
            this.query.order = order === 'ascending' ? 'asc' : (order === 'descending' ? 'desc': '')
            this.handleSearch()
        },
        uploadOk(response, file, fileList) {
            // 这里是element的上传地址，对应的name,url,自己打印fileList对照
            let imgLink = this.qiniuUri + '/' + response.key
            this.imgList.push({ uid: file.uid, url: imgLink});
        },
        editUploadOk(res, file){
            let quill = this.$refs.QuillEditor.quill
            // 如果上传成功
            if (res) {
                let imgLink = this.qiniuUri + '/' + res.key
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片，res为服务器返回的图片链接地址
                quill.insertEmbed(length, 'image', imgLink);
                // 调整光标到最后
                quill.setSelection(length+1);
                quill.focus();
            } else {
                // 提示信息，需引入Message
                this.$message.error('图片插入失败')
            }
        },
        // 移除图片
        handleRemove(file, fileList) {
            this.imgList.forEach((item, index) => {
                if (file.url === item.url) {
                    this.imgList.splice(index, 1);
                }
            });
        },
        getUUID(){
          let date = new Date();
          let year = (date.getFullYear() + '') . substring(2);        //年 ,从 Date 对象以四位数字返回年份
          let month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
          let day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
          month = (month > 9 ? '' : '0')  + month
          day = (day > 9 ? '' : '0')  + day
          let d = date.getTime();
          return year + month  + day + '-xxxxxxxx-xxxx'.replace(/[xy]/g, function (c) {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
          });
        },
        beforeEditUpload(file) {
            this.tokenData.key = this.getUUID() +  file.name.substring(file.name.lastIndexOf('.'))
            return new Promise((resolve, reject) => {
                let _URL = window.URL || window.webkitURL
                let img = new Image()
                img.onload = function () {
                    file.width = img.width // 获取到width放在了file属性上
                    file.height = img.height // 获取到height放在了file属性上
                    let valid = img.width > 500 // 图片宽度大于430
                    if (valid) {
                        imageConversion.compressAccurately(file, {
                            size: 100,
                            width: 500,
                        }).then(res => {
                            resolve(res)
                        })
                    } else {
                        resolve(file)
                    }
                }
                // 需要把图片赋值
                img.src = _URL.createObjectURL(file)
            })
        },
        beforeUpload(file) {
            this.tokenData.key = this.getUUID() +  file.name.substring(file.name.lastIndexOf('.'))
            return new Promise((resolve, reject) => {
                let _URL = window.URL || window.webkitURL
                let img = new Image()
                img.onload = function () {
                    file.width = img.width // 获取到width放在了file属性上
                    file.height = img.height // 获取到height放在了file属性上
                    let valid = img.width > 500 // 图片宽度大于430
                    if (valid) {
                        imageConversion.compressAccurately(file, {
                            size: 80,
                            width: 500,
                            height: 500,
                            //orientation: 6
                        }).then(res => {
                            resolve(res)
                        })
                    } else {
                        resolve(file)
                    }
                }
                // 需要把图片赋值
                img.src = _URL.createObjectURL(file)
            })
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            this.http.getSpus(this.query).then(res => {
                this.tableData = res.data.list;
                this.total = res.data.total;
                this.tableData.forEach(item => {
                    item.cat_id = parseInt(item.cat_id)
                    item.brand_id = parseInt(item.brand_id)
                })
            });

        },
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        // 触发搜索按钮
        handleSearch() {
            if(this.query.name) {
              this.$set(this.query, 'page', 1);
            }
            let moreParam = []
            for (let i = 0; i < this.searchOptions.length; i++) {
                if (this.searchOptions[i].val === '') {
                    continue;
                }
                let _ = Object.assign({}, this.searchOptions[i])
                delete _.name
                moreParam.push(_)
            }
            this.query.more_param = moreParam
            this.getData();
        },
        cancelUpload() {
            this.uploadVisible = false
        },
        saveUpload() {
            let imgArr = []
            this.imgList.forEach(item => {
                imgArr.push(item.url)
            })
            if(this.listImgIdx > 1 && this.listImgIdx > imgArr.length) {
                this.$message.error("主图参数异常, 不能大于图片总数")
                return false
            }
            let postData = {
                img_list: JSON.stringify(imgArr),
                img_idx: this.listImgIdx - 1,
            }
            this.http.saveSpuImg(this.uploadId, postData).then(res => {
                  if(res.code === 0) {
                      this.$message.success("保存上传成功")
                      this.imgList = []
                  }
            })
            this.uploadVisible = false
        },
        saveDetail(){
            let postData = {
                detail_content: this.detailContent.replace(new RegExp('<img src=' , "g"), '<img style="width:100%" src='),
            }
            this.http.saveSpuImg(this.detailId, postData).then(res => {
                if(res.code === 0) {
                    this.$message.success("修改详情成功")
                    this.detailContent = ''
                }
            })
            this.detailVisible = false
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        handleUpload(index, row) {
            this.uploadId = row.id
            this.fileList = []
            this.imgList = []
            this.http.getSpuDetail(this.uploadId).then(res => {
                if( res.data.img_list instanceof Array) {
                    res.data.img_list.forEach((item, idx) => {
                        this.fileList.push({
                            url:  item,
                            name:  'image-' + idx,
                            uid:  idx,
                        })
                        this.imgList.push({uid: idx, url: item });
                    })
                }
            })
            this.uploadVisible = true;
        },
        editDetail(index, row) {
            this.detailId = row.id
            this.http.getSpuDetail(this.detailId).then(res => {
                this.detailContent = res.data.detail_content
            })
            this.detailVisible = true;
        },
        handleAttrEdit(row) {
            this.id = row.id
            this.http.reqSkuAttr(row.id).then(res => {
                this.editOptions = res.data;
            })
            this.editAttrVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.http.editSpu(this.form.id, this.form)
            this.$message.success('修改商品 ' +  this.form.name  + ' 成功');
            this.$set(this.tableData, this.idx, this.form);
        },
        changeState(row){
            let isOnline = row.state === '1'
            row.state = isOnline ? '0': '1'
            this.http.editSpuState(row.id, {state: row.state})
            this.$message.success(  (isOnline ? '下线 ': '上线 ') +  row.name  + ' 成功');
            this.getData()
        },
        delSpu(row){
            this.http.delSpu(row.id)
            this.$message.success('删除成功');
            this.getData();
        }
    }
};
</script>

<style scoped>
.el-row {
    margin-bottom: 20px;
    background-color: #fff;
}

.handle-select {
  width: 46%;
}

.add-dialog-input {
    width: 80%;
}

.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
